package com.athena.framework.annotation;

import com.athena.framework.beanfactory.BeanFactory;
import com.athena.framework.beanfactory.DefaultBeanFactory;
import com.athena.framework.exception.BeanException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * 解析Bean注解
 */
public class BeanParsing implements AnnotationParsing {

    private final static Logger logger = LoggerFactory.getLogger(BeanParsing.class);

    private BeanFactory beanFactory = DefaultBeanFactory.creatBeanFactory();

    /**
     * 开始解析
     */
    @Override
    public void parsing() {
        //查找所有添加有Bean注解的类
        Set<Class<?>> allClass = findAllScanPackgeByAnnotation(Bean.class);
        allClass.forEach(clazz -> newInstance(clazz));
    }

    /**
     * 创建class的实例
     *
     * @param clazz
     */
    private void newInstance(Class<?> clazz) {
        Bean annotation = clazz.getAnnotation(Bean.class);
        String name = annotation.value();
        if (name.length() == 0) {//bean使用默认的名称
            name = clazz.getName();
        }
        if (beanFactory.getBean(clazz.getName()) == null) {
            try {
                beanFactory.addBean(name, clazz.newInstance());
                if (logger.isInfoEnabled()) {
                    logger.info("托管对象：" + name);
                }
            } catch (Exception e) {
                String msg = "创建bean失败：" + clazz.getName() + "\r\n" + e.getMessage();
                logger.error(msg);
                throw new BeanException(msg);
            }
        } else {
            String msg = "bean的名称不是唯一的值:" + name;
            logger.error(msg);
            throw new BeanException(msg);
        }
    }
}
